using Godot;
using Godot.Collections;
using System;

public partial class CInventory : Node
{
	[Signal]
	public delegate void item_changedEventHandler(Item item);
	[Export]
	public int item_count;
	[Export]
	public Array<Item> items = new Array<Item>();
	private Player _player;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		items.Resize(item_count);
		_player = Owner as Player;
		var Game = GetNode<Game>("/root/Game");
		MessageManager _messageManager = Game.get_message_manager();
		_messageManager.DialogAnswer += AnswerDialog;

		foreach(string itemname in (_player.CharacterData as PlayerData).Inventory)
		{
			Item item = Game.LoadItem(itemname);
			add_item(item);
		}
	}

	public void Initialize()
	{
		items.Resize(item_count);
		_player = Owner as Player;

		foreach(string itemname in (_player.CharacterData as PlayerData).Inventory)
		{
			var Game = GetNode<Game>("/root/Game");
			Item item = Game.LoadItem(itemname);
			add_item(item);
		}
	}

	//添加道具
	public void add_item(Item item)
	{
		var empty_index = get_empty_slot_index();
		if (empty_index == -1)
		{return;}
		items[empty_index] = item;
		PlayerData _playerdata = _player.CharacterData as PlayerData;
		_playerdata.Inventory.Add(item.name);
		EmitSignal(SignalName.item_changed, item);
	}

	public void remove_item(Item item)
	{
		items.Remove(item);
		(_player.CharacterData as PlayerData).Inventory.Remove(item.name);
		EmitSignal(SignalName.item_changed, item);
	}

	public int get_empty_slot_index()
	{
		int index = 0;
		foreach (Item slot in items)
		{
			if (slot == null)
			{
				return index;
			}
			index++;
		}
		return -1;
	}

	public void AnswerDialog(string quest, string isAccept)
	{
		
		var Game = GetNode<Game>("/root/Game");
		if(quest.Substring(0,3) == "get"||quest.Substring(0,3) == "los")
		{
			string itemname = quest.Substring(4,quest.Length-4);
			GD.Print("获得",itemname);
			Item item = Game.LoadItem(itemname);
			add_item(item);
		}
	}
}
